import {
  login,
  getMenus,
  logout,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount
} from '@/api/user'
import { setToken, getToken, setRoutes, removeCookieKey, setUserName, getUserName } from '@/libs/util'
import { getMenuList } from '@/libs/set-routers'
import { Message } from 'iview'

export default {
  state: {
    userName: '',
    userId: '',
    menus: [],
    token: '',
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {}
  },
  mutations: {
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
      setUserName(name)
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    setMenus (state, list) {
      state.menus = list
      list.length > 0 && setRoutes(list)
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length,
    getUserName: state => state.userName || getUserName()
  },
  actions: {
    // 登录
    async handleLogin ({ dispatch, commit }, { userName, password }) {
      userName = userName.trim()
      const resp = await login({ userName, password })
      if (resp.data.state === '000') {
        Message.success({
          content: '登录成功',
          duration: 2
        })
        commit('setUserName', resp.data.data.uname)
        commit('setUserId', resp.data.data.id)
        commit('setAccess', 'super_admin')
        commit('setHasGetInfo', true)
        commit('setToken', resp.data.data.token)
      }
      return resp.data
      // return new Promise((resolve, reject) => {
      //   login({
      //     userName,
      //     password
      //   }).then(res => {
      //     const data = res.data
      //     commit('setToken', data.token)
      //     resolve()
      //   }).catch(err => {
      //     reject(err)
      //   })
      // })
    },
    async getMenus ({ commit }) {
      const resp = await getMenus()
      if (resp.data.state === '000') {
        return new Promise((resolve, reject) => {
          const menus = getMenuList(resp.data.data)
          commit('setMenus', menus)
          window.sessionStorage.setItem('mainRoute', resp.data.data[0].uri)
          resolve({ menus, state: '000' })
        })
      } else {
        return Promise.resolve(resp)
      }
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        commit('setToken', '')
        commit('setAccess', [])
        commit('setMenus', [])
        resolve()
      })
    },
    removeCookie () {
      return new Promise((resolve, reject) => {
        removeCookieKey('token')
        removeCookieKey('username')
        removeCookieKey('menus')
        window.sessionStorage.removeItem('report_data')
        resolve()
      })
    },
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    getUnreadMessageCount ({ state, commit }) {
      getUnreadCount().then(res => {
        const { data } = res
        commit('setMessageCount', data)
      })
    },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList ({ state, commit }) {
      return new Promise((resolve, reject) => {
        getMessage()
          .then(res => {
            const { unread, readed, trash } = res.data
            commit(
              'setMessageUnreadList',
              unread.sort(
                (a, b) => new Date(b.create_time) - new Date(a.create_time)
              )
            )
            commit(
              'setMessageReadedList',
              readed
                .map(_ => {
                  _.loading = false
                  return _
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            )
            commit(
              'setMessageTrashList',
              trash
                .map(_ => {
                  _.loading = false
                  return _
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            )
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 根据当前点击的消息的id获取内容
    getContentByMsgId ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', { msg_id, content })
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageUnreadList',
              to: 'messageReadedList',
              msg_id
            })
            commit('setMessageCount', state.unreadCount - 1)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageReadedList',
              to: 'messageTrashList',
              msg_id
            })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageTrashList',
              to: 'messageReadedList',
              msg_id
            })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}
